# coding=utf-8

import sys
import xml.etree.ElementTree as xml

class Importer:
	_xmlFile = ""
	_tree = None
	_root = None

	def __init__(self, xmlFile):
		self._xmlFile = xmlFile
		self._tree = xml.parse(self._xmlFile)
		self._root = self._tree.getroot()

	def getStreams(self):
		listing = []
		for stream in self._root.iter("stream"):
			listing.append([self._toUnicode(stream.attrib["name"]), self._toUnicode(stream.text)])

		return listing

	def editStreamURL(self, station, url):
		changed = False

		for stream in self._root.iter("stream"):
			if stream.get("name") == station:
				stream.text = url
				changed = True

		if changed:
			self._tree.write(self._xmlFile)
	
	def addStation(self, station, url):
		newStation = xml.SubElement(self._root, "stream", {"name" : station})
		newStation.text = url
		self._tree.write(self._xmlFile, "utf-8")

	def removeStation(self, station):
		for stream in self._root.iter("stream"):
			if stream.get("name") == station:
				self._root.remove(stream)
				break
		self._tree.write(self._xmlFile)

	def getURL(self, station):
		url = ""
		for stream in self._root.iter("stream"):
			if stream.get("name") == station:
				url = stream.text

		return url

	def hasStation(self, station):
		for stream in self._root.iter("stream"):
			if stream.get("name") == station:
				return True

		return False

	def _toUnicode(self, obj, encoding="utf-8"):
		if isinstance(obj, basestring):
			if not isinstance(obj, unicode):
				obj = unicode(obj, encoding)
		return obj
